<?php
namespace cubox\provider;

use cubox\Model;

class SQLBuild{

    public  SQLParam $param;
    public function __construct()
    {
        $this->param = new SQLParam();
    }
    /**
     * 新建查询条件
     * 
     * 参数长度1时，只有类型为Array生效，这时生成一个OR查询子串,
     * 
     * 参数长度2时，arg1 = arg2 ，特殊值 null,is null, not null,is no null(只在参数长度2时生效)
     * 
     * 参数长度3时，arg2 请填写运算符，
     * 
     * 支持运算符 =,==,<>,<,<=,>,>=,in,like,is,
     * 
     * 参数1类型是Array时 支持联合查询 ([where1,where2,where3...]) 和字段列表 ([field1,field2,field3...],arg2,arg3)
     * 
     * 参数2是 in 时，参数3支持 string和array两种类型
     * 
     * @param mixed ...$args 填写1到3个参数
     * @return cubox\model
     * 
     */
    public function where(...$args)
    {
        $this->param->where[] = $args;
    }

    public function field(string | array $field = '*'){

        if (is_string($field)) $field = explode(',',$field);
        $this->param->field = array_merge($this->param->field,$field);
    }
    
    public function having(...$args)
    {
        $this->param->having = $args;
    }

    public function alias(string $alias){
        $this->param->alias = $alias;
    }

    public function limit(int $start,int $size = null)
    {
        $this->param->limit = [$start,$size];
    }

    public function order(string $field, string $order = 'ASC')
    {
        $this->param->order[] =  [$field,$order];
    }

    
    public function group(string $field)
    {
        $this->param->group[] =  $field;
    }

    public function join(string|array|Model $table,string $on,string $type = 'left'){
        
        $tableName = $table;

        if ($table instanceof Model){
            $tableName = $table->getTable();
        }

        if (is_array($table)){
            $tableName = array_key_first($table) .' AS ' . $table[array_key_first($table)];
        }
        
        $this->param->join[] = [$type,$tableName,$on];
    }

    public function clear(){
         $this->param = new SQLParam();
    }

   
    


}